﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace GoodStuff.Web
{
    public class LegacyRedirectModule : IHttpModule
    {
        private static List<IRedirectProvider> __providers = new List<IRedirectProvider>();

        public void Dispose()
        {
           
        }

        public static void AddProvider(IRedirectProvider provider)
        {
            __providers.Add(provider);
        }

        public void Init(HttpApplication context)
        {
            //TODO: load configuration section with the provider.


            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;

            HttpRequest request = context.Request;
            
            //find a IRedirectProvider and ask if redirection is required.           
            if (__providers != null)
            {
                string path = VirtualPathUtility.ToAppRelative(request.Path);
                if (request.QueryString != null)
                {
                    path = path + "?" + request.QueryString;
                }
                if (path.EndsWith("?"))
                {
                    path = path.Substring(0, path.Length - 1);
                }

                foreach (IRedirectProvider provider in __providers)
                {
                    string newUrl = provider.DetermineRedirect(path);
                    if (newUrl != null)
                    {
                        //resolve cannot handle querystrings, so split that.
                        string[] parts = newUrl.Split('?');
                        newUrl =  VirtualPathUtility.ToAbsolute(parts[0]);
                        if (parts.Length > 1)
                        {
                            newUrl += "?" + parts[1];
                        }

                        context.Response.Status = "301 Moved Permanently";
                        context.Response.AddHeader("Location", newUrl);
                        context.Response.End();
                    }
                }
            }
        }
    }
}
